<?php
// 自定义语言包
if (!function_exists('my_translate_lang')) {
    function my_translate_lang($text, $lang)
    {
        if (dr_is_app('usu_fanyi')) {
            return \Phpcmf\Service::L('lang', 'usu_fanyi')->fanyi($text, $lang);
        }
        return $text;
    }
}

function usu_fanyi($value, $lang)
{

    if (empty($_COOKIE['language'])) {

        return $value;
    }
    if (preg_match("/<[a-z][\s\S]*>/i", $value) !== 0 && $lang !== 'zh' && $lang !== 'en') {
        $dom = new DOMDocument();
        $dom->loadHTML($value);
        $xpath = new DOMXPath($dom);
        $text_nodes = $xpath->query("//text()");
        foreach ($text_nodes as $node) {
            $translated_text = \Phpcmf\Service::L('lang', 'usu_fanyi')->zhiyi($node->nodeValue, $lang);
            $new_node = $dom->createTextNode($translated_text);
            $node->parentNode->replaceChild($new_node, $node);
        }
        return $dom->saveHTML();
    }

    $pattern = "/<[^>]*>/";
    if (preg_match_all($pattern, $value, $tags) !== 0) {
        return $value;
    }

    if ($lang == 'en') {
        return $value;
    } else {

        if (preg_match_all('/([A-Z][^\.!?]*[\.!?])|\'[^\']*\'|\b[a-zA-Z]+\b/', $value, $mt)) {
            // 说明包含中文

            foreach ($mt[0] as $tt) {
                $text = \Phpcmf\Service::L('lang', 'usu_fanyi')->zhiyi($tt, $lang);
                if ($text) {
                    $value = str_replace($tt, $text, $value);
                }
                // }
            }
        }
    }
    return $value;
}
